package com.king01.service.impl;

import com.king01.dao.MenuDao;
import com.king01.entity.Menu;
import com.king01.entity.Staff;
import com.king01.service.MenuService;
import com.king01.vo.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author ：lqs
 * @date ：Created in 2023/9/25 18:08
 * @description：
 * @modified By：
 * @version:
 */
@Service
public class MenuServiceImpl implements MenuService {
    @Autowired
    private MenuDao menuDao;
    @Autowired
    HttpSession session;
    @Override
    public Result findByUserid() {
        Staff staff= (Staff) session.getAttribute("staff");
        List<Menu> list = menuDao.selectByUserId(staff.getStaffid());
        //找到一级菜单
        List<Menu> firsts=new ArrayList<Menu>();
        for(Menu m:list){
            if(m.getMpid()==0){
                firsts.add(m);
            }
        }
        System.out.println("firsts-----"+firsts);
        //找到一级菜单对应的二级菜单
        for(Menu f:firsts){
            List<Menu> children=new ArrayList<Menu>();
            for(Menu m:list){
                if(m.getMpid().equals(f.getMid())){
                    children.add(m);
                }
            }
            f.setChildren(children);
        }

        return new Result(200,"查询左侧菜单成功",firsts);
    }

    @Override
    public Result findMenuByRoleId(Integer id) {
//        查询所有菜单
        List<Menu> list = menuDao.selectAllMenu();
        //找到一级菜单
        List<Menu> firsts = new ArrayList<Menu>();
        for (Menu m : list) {
            if (m.getMpid() == 0) {
                firsts.add(m);
            }
        }
        System.out.println("firsts-----" + firsts);
        //找到一级菜单对应的二级菜单
        for (Menu f : firsts) {
            List<Menu> children = new ArrayList<Menu>();
            for (Menu m : list) {
                if (m.getMpid().equals(f.getMid())) {
                    children.add(m);
                }
            }
            f.setChildren(children);
        }

//        查询当前角色具有的菜单id
        List<Integer> mids = menuDao.selectMidByRoleid(id);

//        把上面的所有菜单以及该角色而具有的菜单id封装到map中
        Map<String,Object> map = new HashMap<>();
        map.put("firsts",firsts);
        map.put("mids",mids);
        return new Result(200,"查询成功",map);
    }

    @Override
    public Result fenPx(Integer roleid, Integer[] ids) {
//        删除该角色原来具有的权限
        menuDao.deleteByRoleId(roleid);
//        添加新的权限
        menuDao.insertNew(roleid,ids);
        return new Result(200,"分配权限成功",null);
    }

}

